package com.ideabove.heart;





import java.util.Calendar;
import java.util.Hashtable;
import java.util.Timer;

import com.ideabove.heart.db.DBHelper;
import com.ideabove.heart.db.Database;
import com.ideabove.heart.manager.AppManager;
import com.ideabove.heart.manager.MoeManager;
import com.ideabove.heart.manager.ScheduleManager;
import com.ideabove.heart.util.LogUtil;
import com.ideabove.heart.util.MyUtil;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;

public class MorningCallActivity extends MyActivity {
	Activity mActivity;
	int mcount = 0;
	MediaPlayer mplayer = new MediaPlayer();
	Timer mTimer;
	
	boolean isFailArarm = true;
	int mVolum;
	float mVolumPersent = 0.7f;
	int beforeRingerMode;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		DBHelper dbHelper = new DBHelper(this);
		Hashtable<String,String> alarmInfo = dbHelper.getAlarmInfo();
		
		if(!"1".equals( alarmInfo.get(Database.AlarmSetTable.ISUSE) )){
			finish();
			return;			
		}
		
		setContentView(R.layout.receive_call);		
		
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED 
				| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD 
				| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON 
				| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); 

		mActivity = this;
			
		AppManager.pause(MorningCallActivity.this);
		
		AudioManager aManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		beforeRingerMode = aManager.getRingerMode(); 
		
		
//		mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL
		
		aManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
//		aManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
//		aManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
		
		
		// 텍스트
		final TextView textView = (TextView)findViewById(R.id.main_calling_txt);
		MyUtil.blinkText(textView, 700);
		
		try {

			Uri alert =  RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
			
			mplayer.setDataSource(this, alert);
			
			final AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
			mVolum = audio.getStreamMaxVolume(AudioManager.STREAM_RING);						
			audio.setStreamVolume(
					AudioManager.STREAM_RING, 
					(int)(mVolum * mVolumPersent), // 90% 볼륨 다틀려 Max 값이 기기마다 
					AudioManager.FLAG_PLAY_SOUND);

			mplayer.setAudioStreamType(AudioManager.STREAM_RING);
			mplayer.setOnCompletionListener(new OnCompletionListener() {
				
				@Override
				public void onCompletion(MediaPlayer mp) {
					// TODO Auto-generated method stub
					mplayer.start();
					
					if( mcount > 1){
						mplayer.stop();
						setFailAlarm();
						finish();
						return;
					}
					mcount++;

				}
			});
			
			mplayer.setOnSeekCompleteListener(new OnSeekCompleteListener() {

				@Override
				public void onSeekComplete(MediaPlayer mp) {
					// TODO Auto-generated method stub

					
					if( mcount > 1){
						mplayer.stop();
						setFailAlarm();
						finish();
						return;
					}
					mcount++;

					 
				}
			});
			mplayer.prepare();
			mplayer.start();
			
//			Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);        			
//			long[] pattern = {1000, 200, 1000, 2000, 1200};          // 진동, 무진동, 진동 무진동 숫으로 시간을 설정한다.
//			vibe.vibrate(1000);
			
			//vibe.vibrate(pattern, 0);                                         // 패턴을 지정하고 반복횟수를 지정
			//vibe.vibrate(1000);                                                   //1초 동안 진동이 울린다.

			
		} catch(Exception e) {
		}   

		final ImageView image = (ImageView)findViewById(R.id.hang_up_btn);
		image.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				setSucessAlarm();
				
				if(mplayer != null){
					mplayer.stop();
				}
				
				if(mTimer != null){
					mTimer.cancel();
				}
				
			}
		});
		
	}
	
	// 알람 성공시 DB에 성공 여부를 기록한다.
	public void setSucessAlarm(){
		isFailArarm = false;
		
		if(ScheduleManager.getStoryOnOff(this)){
			// 스토리모드 On
			// 알람 성공 시간 기록
			ScheduleManager sm = new ScheduleManager(MorningCallActivity.this);
			sm.updateAlarmSucess(Calendar.getInstance().getTimeInMillis());

			// 다음스케쥴을 추가한다.
			sm.insertNextEpisode(0, ScheduleManager.STORY_START);
			MoeManager.setWhatWillIdo(MoeManager.DO_STORY);
			
			Intent intent = new Intent(MorningCallActivity.this, MoeActivity.class);
			mActivity.startActivity(intent);
			mActivity.finish();
		}else{
			// 스토리모드 Off
			MoeManager.setWhatWillIdo(MoeManager.DO_STORY_OFF);
			
			Intent intent = new Intent(MorningCallActivity.this, MoeActivity.class);
			mActivity.startActivity(intent);
			mActivity.finish();
		}		
	}
	
	// 알람 실패시 반복 알람( 부재중 통화이냐 아님 다시 5분후에 울리는가를 결정한다)
	public void setFailAlarm(){
		
		if(isFailArarm){
			ScheduleManager sm = new ScheduleManager(MorningCallActivity.this);
			Hashtable<String, String> info = sm.getAlarmInfo();
			
			final int repeatCnt = Integer.parseInt(info.get(Database.AlarmSetTable.REPEATE));
			final int interval = 5;//Integer.parseInt(info.get(Database.AlarmSetTable.INTERVAL));
			final int failCnt = Integer.parseInt(info.get(Database.AlarmSetTable.FAILCNT));
			
	
			// 반복이냐 부재중이냐를 결정
			if(failCnt >= repeatCnt){
				// 부재중설정				
				Intent intent = new Intent(MorningCallActivity.this, FailActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
				mActivity.startActivity(intent);
				mActivity.finish();
			}else{
				// 반복알람 설정				
				Calendar dateTime = Calendar.getInstance();
				int setMinute = dateTime.get(Calendar.MINUTE) + interval;
				dateTime.set(Calendar.MINUTE, setMinute);				
				sm.setAlarmJustOneTime(dateTime.getTimeInMillis());								
			}

			// failCnt + 1 (실패 횟수를 넣는다)
			sm.updateAlarmFail(Integer.parseInt(info.get(Database.AlarmSetTable._ID)), failCnt + 1);
			
			
		}
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onStart();
		AppManager.pause(MorningCallActivity.this);
	}
	
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		AppManager.pause(MorningCallActivity.this);
	}

	@Override
	protected void onDestroy() {
		
		// TODO Auto-generated method stub
		AudioManager aManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		aManager.setRingerMode(beforeRingerMode);
		
		AppManager.pause(MorningCallActivity.this);
		mplayer.stop();
		super.onDestroy();
	}



	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
//			finish();			
//			Intent iAlarm = new Intent(this, MainActivity.class);	
//			iAlarm.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//			startActivity(iAlarm);  
			break;
		}
		return true;
	}




		public void checkAndStartAlarm(){
			Intent intento = getIntent();

			if(intento == null || intento.getExtras() == null){

				Log.e("#########1", "####" + intento);
				if(intento != null)
					Log.e("#########2", "####" + intento.getExtras());
				return;
			}

			String query = intento.getExtras().getString("q");

			Log.e("#########3", "####" + query);
			if("alarm_start".equals(query)){
				Intent intent = new Intent(this, MoeActivity.class);
				startActivity(intent);			
			}
		}


	}
